#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2025/6/16 16:44
# @Author  : Chenmm
# @File    : models.py
# @Software: PyCharm

from sqlalchemy import Column, Integer, String, ForeignKey, Boolean, Text, DateTime
from sqlalchemy import MetaData
from sqlalchemy.inspection import inspect
from datetime import datetime

from sqlalchemy.orm import DeclarativeMeta

from middlewares.mysql.database import Base, engine


class Role(Base):
    """角色"""
    __tablename__ = "roles"

    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(length=8), unique=True, index=True)  # 角色名称


class User(Base):
    """用户基础表"""
    __tablename__ = "users"

    id = Column(Integer, primary_key=True, index=True)
    username = Column(String(length=32), unique=True, index=True)  # 用户名
    password = Column(String(length=252))  # 密码
    status = Column(Integer, default=0)  # 删除，0正常
    job_num = Column(String(252), unique=True, nullable=True)  # 工号
    student_num = Column(String(252), unique=True, nullable=True)  # 学号
    age = Column(Integer)  # 年龄
    sex = Column(String(length=8), default="男")  # 性别
    role = Column(Integer, ForeignKey('roles.id'))  # 角色
    add_time = Column(DateTime, default=datetime.now())


class Course(Base):
    """课程"""
    __tablename__ = "courses"

    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(length=252), unique=True, index=True)  # 课程名称
    icon = Column(String(length=252), nullable=True)  # icon
    desc = Column(String(length=252), nullable=True)  # 描述
    status = Column(Boolean, default=False)  # 状态
    onsale = Column(Boolean, default=False)  # 是否上架
    catalog = Column(Text, nullable=True)  # 目录
    owner = Column(Integer, ForeignKey('users.id'))  # 拥有者
    like_num = Column(Integer, default=0)  # 点赞


class StudentCourse(Base):
    """学生课程"""
    __tablename__ = "student_courses"

    id = Column(Integer, primary_key=True, index=True)
    student = Column(Integer, ForeignKey('users.id'))  # 学生
    course = Column(Integer, ForeignKey('courses.id'))  # 课程
    add_time = Column(DateTime, default=datetime.now())
    update_time = Column(DateTime, default=datetime.now())
    status = Column(Integer, default=0)  # 1.删除，0.正常


class CourseComment(Base):
    """课程评论"""
    __tablename__ = "course_comments"

    id = Column(Integer, primary_key=True, index=True)
    course = Column(Integer, ForeignKey('courses.id'))  # 课程
    user = Column(Integer, ForeignKey('users.id'))  # 评论人
    pid = Column(Integer)  # 回复
    add_time = Column(DateTime, default=datetime.now())
    top = Column(Boolean, default=False)  # 是否置顶
    context = Column(Text)
    status = Column(Boolean, default=0)  # 1删除0正常


class Message(Base):
    __tablename__ = "messages"

    id = Column(Integer, primary_key=True, index=True)
    send_user = Column(Integer, ForeignKey('users.id'))  # 发送者
    accept_user = Column(Integer, ForeignKey('users.id'))  # 接收者
    read = Column(Boolean, default=False)  # 是否已读，接收者是否已读
    send_time = Column(String(length=252))  # 发送时间
    pid = Column(Integer)  # 回复消息的id
    add_time = Column(DateTime, default=datetime.now())  # 添加时间
    context = Column(Text)
    status = Column(Integer, default=0)  # 1删除0正常


def create_tables():
    """表不存在则创建"""
    global_dict = globals()
    classes = [v
               for k, v in global_dict.items()
               if callable(v) and isinstance(v, DeclarativeMeta) and hasattr(v, "__tablename__")]
    metadata = MetaData()
    for _cls in classes:
        if not inspect(engine).has_table(_cls.__tablename__, schema=None, metadata=metadata):
            _cls.__table__.create(bind=engine)
            print(f"表：‘{_cls.__tablename__}’ 创建完成！")
        else:
            print(f"表：‘{_cls.__tablename__}’ 已存在！")


def init_roles():
    from middlewares.mysql.database import SessionLocal
    db = SessionLocal()
    exists = db.query(Role).all()
    if exists:
        print("roles already init")
        db.close()
        return
    for index, sex in enumerate(("老师", "学生")):
        role = Role(id=index+1, name=sex)
        db.add(role)
        db.commit()
        db.refresh(role)
    db.close()



if __name__ == '__main__':
    create_tables()
    init_roles()